package com.sk.weichat.helper;

import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.widget.EditText;
import android.widget.ToggleButton;

public class PasswordHelper {
    private static final int INVISIBLE_TYPE = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
    private static final int VISIBLE_TYPE = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;

    private PasswordHelper() {
    }

    public static void bindPasswordEye(EditText et, ToggleButton eye) {
        // checked 为 true表示眼睛睁开可以看见密码的情况，
//        et.setInputType(INVISIBLE_TYPE);
        et.setTransformationMethod(PasswordTransformationMethod.getInstance());
        eye.setChecked(false);
        eye.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
//                et.setInputType(VISIBLE_TYPE);
                et.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                //设置光标在末尾
                CharSequence charSequence = et.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }
            } else {
//                et.setInputType(INVISIBLE_TYPE);
                et.setTransformationMethod(PasswordTransformationMethod.getInstance());
                //设置光标在末尾
                CharSequence charSequence = et.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }
            }
        });
    }
}
